import {Component, ElementRef, ViewChild, Renderer2} from '@angular/core';
import {
    ActionSheetController,
    IonicPage,
    NavController,
    NavParams,
    Platform,
    LoadingController,
    Loading, Events
} from 'ionic-angular';
import {AuthService} from "../../../services/common/auth.service";
import {HeadPortraitSettingProvider} from "../../../providers/me/head-portrait-setting/head-portrait-setting.provider";
import {Camera} from '@ionic-native/camera';
import {FileService} from "../../../services/native/file/file.service";
import {ToastService} from "../../../services/common/toast.service";
import {FileTransfer} from '@ionic-native/file-transfer';
import {LocalStorageService} from "../../../services/native/local-storage/local-storage.service";
import {Base64ToGallery} from '@ionic-native/base64-to-gallery';
import {SettingProvider} from "../../../providers/me/setting/setting.provider";
import {UnlockService} from "../../../services/native/authentication/authentication.service";
import {File} from "@ionic-native/file";
import {Device} from "@ionic-native/device";
import {AppVersion} from "@ionic-native/app-version";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";
import {VersionService} from "../../../services/common/version.service";
import {PermissionsService} from "../../../services/native/permissions/permissions.service";
import {CacheImgService} from "../../../services/native/cache-img/cache-img.service";
import {Network} from "@ionic-native/network";

@IonicPage()
@Component({
    selector: 'page-setting',
    templateUrl: 'setting.html',
    providers: [
        HeadPortraitSettingProvider,
        Camera,
        FileService,
        ToastService,
        FileTransfer,
        VersionService,
        LocalStorageService,
        Base64ToGallery,
        File,
        Device,
        PermissionsService,
        SettingProvider
    ]
})
export class SettingPage {
    private defaultAvatar = './assets/images/common/icon_headportrait_default.png'; // 用户默认头像
    /*手势密码 */
    private graphicLockTitle: string = '未启用';
    fingerprintSettingVisible: boolean;
    fingerprintSettingTitle: string;
    private avatorUrl;
    private nickName;
    private version: string = "";
    loading: Loading;
    //
    @ViewChild("settingmaincontainer") mainContainer: ElementRef;
    @ViewChild("settingoptionpanel") optionPanel: ElementRef;
    @ViewChild("settinglogoimage") _logoPanelRef: ElementRef;


    constructor(public navCtrl: NavController,
                private authService: AuthService,
                private headPortraitProvider: HeadPortraitSettingProvider,
                private actionSheetCtrl: ActionSheetController,
                private platform: Platform,
                public device: Device,
                private fileService: FileService,
                private toastService: ToastService,
                private unlockService: UnlockService,
                private settingProvider: SettingProvider,
                public loadCtr: LoadingController,
                public navParams: NavParams,
                private appversion: AppVersion,
                private renderer: Renderer2,
                private versionService: VersionService,
                private events: Events,
                private permissionsService: PermissionsService,
                private adpActionSheetController: AdpActionSheetController,
                private cacheImg: CacheImgService,
                public network: Network) {
        this.isOpenGraphicLock();
        this.checkFingerprint();
    }

    ionViewDidLoad() {
    }

    /*获取头像与昵称*/
    public initAuthInfo() {
        let headImage = localStorage.getItem('profileURL');
        this.nickName = localStorage.getItem('nickName');
        if (!headImage) {
            this.avatorUrl = this.defaultAvatar;
            return;
        }

        this.fileService.getAzureInfo().subscribe((data) => {
            // this.avatorUrl = this.fileService.getCompletePath(headImage, data.azureInfo);
            this.cacheImg.getImgPath(headImage, data.azureInfo)
                .then((res) => {
                    this.avatorUrl = res;
                })
                .catch(err => {
                    console.log(err);
                });
        });
    }

    ionViewDidEnter() {
        this.initAuthInfo();
        this.isOpenGraphicLock();
        this.checkFingerprint();
        this.initVersion();
        this.setLogoHeight();
    }

    /*判断是否开启手势密码*/
    isOpenGraphicLock() {
        this.unlockService.isGraphicEnabled().then(enabled => {
            this.graphicLockTitle = enabled ? '设置' : '未启用';
        }).catch(() => {
        });
    }

    setLogoHeight() {
        setTimeout(() => {
            let emptyHeight = this.mainContainer.nativeElement.scrollHeight - this.optionPanel.nativeElement.scrollHeight;
            console.log("mainContainer height:" + this.mainContainer.nativeElement.scrollHeight + "option height:" + this.optionPanel.nativeElement.scrollHeight);
            this._logoPanelRef.nativeElement.setAttribute('style', 'height: ' + emptyHeight + 'px !important;display:block !important;');
            console.info(this._logoPanelRef.nativeElement)
        }, 0);
    }

    async checkFingerprint() {
        this.fingerprintSettingVisible = await this.unlockService.isFingerprintAvailable();
        this.fingerprintSettingTitle = (await this.unlockService.isFingerprintEnabled()) ? '设置' : '未启用';
    }

    initVersion() {
        this.appversion.getVersionNumber().then(currentVersion => {
            this.version = currentVersion;
        }).catch(() => {
        });
    }

    checkNewstVersion() {
        let platformType = "";
        if (this.platform.is('ios')) {
            platformType = 'IOS';
        } else if (this.platform.is('android')) {
            platformType = 'ANDROID';
        }
        console.log("this platform is:" + platformType);
        if (platformType != '') {
            this.versionService.getNewestVersion(this.version, platformType).subscribe(res => {
                if (res.version == this.version) {
                    this.toastService.showToast("已是最新版本");
                } else {
                    console.log("push event to check");
                    this.events.publish('checkVersion', res, 'handCheck');
                }
            }, error2 => {
                if (error2.status == 500 && error2.error != null) {
                    let errorObj = error2.error;
                    if (errorObj.status == 999 && errorObj.exception == "无可用版本") {
                        this.toastService.showToast("已是最新版本");
                    } else {
                        this.toastService.showToast(errorObj.exception);
                    }
                } else {
                    // this.toastService.showToast("啊哦，服务器开小差了，请稍后重试");
                }
            });
        }

    }

    goDetailPage(pageName, params?) {
        this.navCtrl.push(pageName, params)
    }

    goModifyNickNamePage() {
        this.goDetailPage('NickNameSettingPage', {
            nickName: this.nickName
        });
    }

    /*打开头像设置*/
    showModifyHeadPortrait(ev) {
        this.adpActionSheetController.create({
            cssClass: 'roster-action',
            title: '头像',
            buttons: [
                {
                    text: '拍照',
                    handler: () => {
                        this.getPicture(1);
                    }
                },
                {
                    text: '从手机相册上传',
                    handler: () => {
                        this.getPicture(0);
                    }
                },
                {
                    text: '取消',
                    role: 'cancel'
                }
            ]
        }).present();
        ev.stopPropagation();
    }

    getPicture(type) { // 1拍照,0从图库选择
        if (this.platform.is('android')) {
            this.permissionsService.checkCameraAndroidPermission().then(res => {
                if (res) {
                    this.startGetPic(type);
                } else {
                    this.permissionsService.getAndroidCameraPermission().then(res => {
                        if (res == 'authorized' || res == 'GRANTED') {
                            this.startGetPic(type);
                        } else {
                            this.toastService.showToast('请到“设置>应用”中启用“相机”和“存储”权限', 2000);
                        }
                    }).catch(() => {
                        this.toastService.showToast('请到“设置>应用”中启用“相机”和“存储”权限', 2000);
                    });
                }
            })
        } else {
            this.permissionsService.checkIosCameraPermission().then(res => {
                if (res) {
                    this.startGetPic(type);
                } else {
                    this.permissionsService.getIosCameraPermission().then(res => {
                        if (res != 'authorized') {
                            this.toastService.showToast('请到“设置>隐私”启用“相机”', 2000);
                        }
                    }).catch(() => {
                        this.toastService.showToast('请到“设置>隐私”启用“相机”', 2000);
                    });
                }
            })
        }
    }

    private startGetPic(type) {
        if (type == 1) {
            this.headPortraitProvider.getPictureByCamera().subscribe((imageUrl) => {
                this.getPictureSuccess(imageUrl);
            });
        } else {
            this.headPortraitProvider.getPictureByPhotoLibrary().subscribe(imageUrl => {
                this.getPictureSuccess(imageUrl);
            });
        }
    }

    private getPictureSuccess(imageUrl) {
        //首先去除最后一个问号
        let lastIndex = imageUrl.lastIndexOf('?');
        if (lastIndex !== -1) {
            imageUrl = imageUrl.substr(0, lastIndex);
        }

        let lastIndex2 = imageUrl.lastIndexOf('/') + 1;
        let imgName = imageUrl.substr(lastIndex2);
        this.uploadHeadPic(imageUrl, imgName);
    }

    /**
     * 显示加载提示
     */
    showLoading() {
        this.loading = this.loadCtr.create({
            spinner: 'circles',
            content: "正在上传头像"
        });
        this.loading.present();
    }

    /**
     * 关闭加载提示
     */
    dismissLoading() {
        if (this.loading) {
            this.loading.dismiss();
        }
    }

    private getNewGUIDString() {
        let d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now(); //use high-precision timer if available
        }
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
            let r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
    }

    /**
     * 1、上传图片信息到Azure服务器  2、上传文件名到微服务器中
     * @param imageUrl 文件路径
     * @param imgName 文件名
     */
    private uploadHeadPic(imageUrl, imgName) {
        const uploadHeadPicFailMsg = '上传头像失败';
        const uploadHeadPicSucMsg = '上传头像成功';
        /*检查网络*/
        let net_type = this.network.type;
        if (net_type !== "none") { this.showLoading(); }
        let newImageName = this.getNewGUIDString() + '.jpg';
        this.fileService.saveImageFile(imageUrl, imgName, newImageName, this.fileService.getMimeType('.jpg')
        ).subscribe(() => {
            this.fileService.getFilePath(newImageName).subscribe((item) => {
                this.settingProvider.saveHeadPic(newImageName).subscribe(() => {
                    localStorage.setItem('profileURL', newImageName);
                    this.avatorUrl = item.sasUrl;
                    this.dismissLoading();
                    this.toastService.showToast(uploadHeadPicSucMsg, 2000);
                }, (error) => {
                    this.dismissLoading();
                    if (error.status == 500) {
                        this.toastService.showToast(uploadHeadPicFailMsg, 2000);
                    }
                },);
            }, (error) => {
                this.dismissLoading();
                if (error.status == 500) {
                    this.toastService.showToast(uploadHeadPicFailMsg, 2000);
                }
            }, () => {
                this.dismissLoading();
            });
        }, (error) => {
            this.dismissLoading();
            if (error.status == 500) {
                this.toastService.showToast(uploadHeadPicFailMsg, 2000);
            }
        });
    }

    isCordova() {
        return this.platform.is('cordova');
    }

    clearCache() {
        this.cacheImg.clearCache()
            .then((res) => {
            })
            .catch((err) => {
                console.log(err);
            });
    }
}
